<template>
    <div class="role-list defaultBg">
        <div v-loading="loading" v-if="loading" class="loading"></div>
        <my-table
            :tableColumns="tableColumns"
            :isInline="true"
            :tableList="roleList"
            :searchData="searchData"
            :searchButtonList="searchButtonList"
            :tableButtonList="tableButtonList"
            :count="roleCount"
            @sizeChange="sizeChange"
            @pageChange="pageChange">
        </my-table>

        <!-- 编辑角色信息弹窗 -->
        <el-dialog title="编辑角色信息" :visible.sync="editRoleDialogVisible" width="30%">
            <!-- 编辑表单 -->
            <el-form :model="editRoleForm" :rules="editRoleRules" ref="editRoleForm">
                <el-form-item label="角色编码" prop="roleCode" :label-width="formLabelWidth">
                    <el-input v-model="editRoleForm.roleCode" disabled autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
                    <el-input v-model="editRoleForm.roleName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc" :label-width="formLabelWidth">
                    <el-input v-model="editRoleForm.roleDesc" type="textarea" :rows="3" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editRoleFormCancel">取 消</el-button>
                <el-button type="primary" @click="editRoleFormPost">更 改</el-button>
            </div>
        </el-dialog>

        <!-- 更改菜单权限弹窗 -->
        <el-dialog title="更改角色菜单权限" :visible.sync="editMenuDialogVisible" width="40%">
            <el-tree
                :data="allMenuList"
                show-checkbox
                node-key="id"
                ref="menuTree"
                highlight-current
                default-expand-all
                :props="defaultProps">
            </el-tree>

            <div slot="footer" class="dialog-footer">
                <el-button @click="editMenuCancel">取 消</el-button>
                <el-button type="primary" @click="editMenuPost">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 删除角色弹窗 -->
        <el-dialog title="删除角色" :visible.sync="deleteRoleFormVisible" width="33%" :beforeClose="deleteRoleCancel">
            <p class="tip-contant">
                <i class="el-icon-warning icon"></i>
                删除角色需要给绑定此角色的所有用户，重新绑定一个新的角色
            </p>

            <el-form :model="deleteRoleForm" :rules="deleteRoleRules" ref="deleteRoleForm">
                <el-form-item label="请选择新角色" prop="newRoleCode" :label-width="formLabelWidth">
                    <el-select v-model="deleteRoleForm.newRoleCode" placeholder="请选择角色">
                        <el-option
                            v-for="item in newRoleOptions"
                            :key="item.id"
                            :label="item.roleName"
                            :value="item.roleCode">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="deleteRoleCancel">取 消</el-button>
                <el-button type="primary" @click="deleteRolePost">确 定</el-button>
            </div>
        </el-dialog>

        <!-- 新增角色表单 -->
        <el-dialog title="新增用户" :visible.sync="addRoleDialogVisible" width="30%" :beforeClose="addRoleFormCancel">
            <!-- 新增表单 -->
            <el-form :model="addRoleForm" :rules="addRoleRules" ref="addRoleForm">
                <el-form-item label="角色编码" prop="roleCode" :label-width="formLabelWidth">
                    <el-input v-model="addRoleForm.roleCode" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色名称" prop="roleName" :label-width="formLabelWidth">
                    <el-input v-model="addRoleForm.roleName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色描述" prop="roleDesc" :label-width="formLabelWidth">
                    <el-input v-model="addRoleForm.roleDesc" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="菜单权限" prop="menu" :label-width="formLabelWidth">
                    <el-button @click="slectMenu">选择菜单</el-button>
                    <el-dialog
                        width="30%"
                        title="选择菜单"
                        :visible.sync="innerMenuVisible"
                        append-to-body>
                        <el-tree
                            :data="allMenuList"
                            show-checkbox
                            node-key="id"
                            ref="addMenuTree"
                            highlight-current
                            default-expand-all
                            :props="defaultProps">
                        </el-tree>
                        <div slot="footer" class="dialog-footer">
                            <el-button @click="selectMenuCancel">取 消</el-button>
                            <el-button type="primary" @click="selectMenuPost">确 定</el-button>
                        </div>
                    </el-dialog>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addRoleFormCancel">取 消</el-button>
                <el-button type="primary" @click="addRoleFormPost">提 交</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { getRoleList, deleteRole, modifyRoleInfo, getAllMenuList, modifyMenu, addRole } from '@/api/role'
export default {
    name: 'role-list',
    computed: {
    },
    data () {
        return {
            // 搜索框的数据
            searchData: [
                { type: 'text', name: 'roleName', label: '角色名', value: '' },
                { type: 'text', name: 'roleCode', label: '角色编码', value: '' },
            ],
            // 搜索栏按钮数据
            searchButtonList: [
                {
                    id: 'search',
                    name: '查询',
                    type: 'primary',  // primary/warning/danger/success
                    icon: 'el-icon-search',
                    size: 'small',
                    click: (btnList, that) => {
                        // this 当前vue页面
                        // btnList 当前的 searchButtonList数组
                        // that mForm表单页面的this
                        this.getList(that.mform)
                    }
                },
                {
                    id: 'reset',
                    name: '重置',
                    type: '',  // primary/warning/danger/success
                    icon: 'el-icon-refresh-right',
                    size: 'small',
                    click: (btnList, that, parent) => {
                        // this 当前vue页面
                        // btnList 当前的 searchButtonList数组
                        // that mForm表单页面的this
                        this.getList()
                        this.searchData.forEach(item => {
                            that.$set(that.mform, item.name, item.value)
                        })
                    }
                }
            ],

            // 表格头
            tableColumns: [
                { name: 'roleName', label: '角色名称', width: '200' },
                { name: 'roleCode', label: '角色编码', width: '220' },
                // { name: 'menu', label: '菜单', width: '220' },
                { name: 'roleDesc', label: '角色描述', width: '220' },
                {
                    name: 'operation', label: '操作', align: "center",
                    /**
                     * @param {Object} h 渲染函数参数对象
                     * @param {Number} index 该行下角标
                     * @param {Object} row 所在行对象
                     * @param {Object} column 所在列对象
                     * @param {Object} scope 表格项对象
                    */
                    render: (h, index, row, column, scope) => {
                        return (
                            <span>
                                <el-button icon="el-icon-edit-outline" disabled={row.roleCode === 'super_admin'} size="small" type="primary" nativeOn-click={(e) => {
                                    this.editRoleDialogVisible = true
                                    this.editRoleForm.roleCode = row.roleCode
                                    this.editRoleForm.roleName = row.roleName
                                    this.editRoleForm.roleDesc = row.roleDesc
                                    e.stopPropagation() // 阻止事件冒泡，避免表格行被选中
                                }}>编辑</el-button>

                                <el-button icon="el-icon-edit" disabled={row.roleCode === 'super_admin'} size="small" type="warning" nativeOn-click={(e) => {
                                    // 获取全部菜单项
                                    this.getAllMenuList()
                                    this.modifyMenuRoleCode = row.roleCode
                                    // 获取当前角色的菜单权限
                                    this.currentRoleMenuList = row.menu.split(',')
                                    this.editMenuDialogVisible = true
                                    this.$nextTick(() => {
                                        let tempList = this.currentRoleMenuList.filter(item => { return item != 21 && item != 31 })
                                        this.$refs.menuTree.setCheckedKeys(tempList)
                                    })
                                    e.stopPropagation() // 阻止事件冒泡，避免表格行被选中
                                }}>更改菜单权限</el-button>

                                <el-button icon="el-icon-delete" disabled={row.roleCode === 'super_admin'} size="small" type="danger" nativeOn-click={(e) => {
                                    this.deleteRoleForm.roleCode = row.roleCode
                                    this.newRoleOptions = this.roleList.filter(item => { return item.roleCode !== row.roleCode })
                                    this.deleteRoleFormVisible = true
                                    e.stopPropagation() // 阻止事件冒泡，避免表格行被选中
                                }}>删除</el-button>
                            </span>
                        )
                    },
                }
            ],
            // 表格按钮
            tableButtonList: [
                {
                    id: 'add',
                    name: '添加角色',
                    type: 'primary',  // primary/warning/danger/success
                    icon: 'el-icon-plus',
                    size: 'small',
                    click: (btnList, that) => {
                        // this 当前vue页面
                        // btnList 当前的 searchButtonList数组
                        // that mForm表单页面的this
                        this.addRoleDialogVisible = true
                    }
                }
            ],
            // 表格内容
            roleList: [],
            // 数据是否准备完毕
            dataIsReady: false,

            formLabelWidth: '120px',

            // 编辑角色信息弹窗配置
            editRoleDialogVisible: false,
            editRoleForm: {
                roleCode: '',
                roleName: '',
                roleDesc: ''
            },
            editRoleRules: {
                roleCode: [
                    { required: true, message: '缺少角色编码', trigger: 'blur' },
                ],
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
                ],
                roleDesc: []
            },

            // 删除角色弹窗配置
            deleteRoleFormVisible: false,
            deleteRoleForm: {
                roleCode: '',
                newRoleCode: ''
            },
            deleteRoleRules: {
                roleCode: [
                    { required: true, message: '请选择一个角色', trigger: 'change' },
                ],
                newRoleCode: [
                    { required: true, message: '请选择一个角色', trigger: 'change' },
                ]
            },
            newRoleOptions: [],

            // 更改角色菜单权限弹窗配置
            editMenuDialogVisible: false,
            modifyMenuRoleCode: '',
            allMenuList: [], // 全部菜单项
            currentRoleMenuList: [], // 当前角色的菜单项

            defaultProps: {
                children: 'children',
                label: 'title'
            },

            // 新增角色弹窗配置
            addRoleDialogVisible: false,
            innerMenuVisible: false,
            addRoleForm: {
                roleCode: '',
                roleName: '',
                menu: '',
                roleDesc: '',
            },
            addRoleRules: {
                roleCode: [
                    { required: true, message: '缺少角色编码', trigger: 'blur' }
                ],
                roleName: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                    { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
                ],
                menu: [
                    { required: true, message: '请至少选择一个菜单项', trigger: 'blur' },
                ],
            },
            // 列表数据是否准备完
            loading: true,
            // 当前页码
            offect: 1,
            // 当前列表显示条数
            limit: 10,
            // 表格长度
            roleCount: 0
        }

    },
    methods: {
        // 获取角色列表
        async getList (searchData = {}) {
            searchData.limit = this.limit
            searchData.offect = this.offect
            const { data } = await getRoleList(searchData)
            this.roleList = data.resList
            this.roleCount = data.count
            this.dataIsReady = true
            this.loading = false
        },

        // 删除角色取消
        deleteRoleCancel () {
            this.deleteRoleFormVisible = false
            this.$refs.deleteRoleForm.resetFields()
        },

        // 删除角色提交
        deleteRolePost () {
            this.$refs.deleteRoleForm.validate(async (valid) => {
                if (valid) {
                    const res = await deleteRole(this.deleteRoleForm)
                    if (res.hasOk) {
                        this.$message({
                            message: '角色删除成功',
                            type: 'success'
                        })
                        // 重置表格
                        this.getList()
                        this.deleteRoleFormVisible = false
                        this.$refs.deleteRoleForm.resetFields()
                    } else {
                        this.$message({
                            message: res.message,
                            type: 'error'
                        })
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },

        // 编辑角色信息取消
        editRoleFormCancel () {
            this.editRoleDialogVisible = false
        },

        // 编辑角色信息提交
        editRoleFormPost () {
            this.$refs.editRoleForm.validate(async (valid) => {
                if (valid) {
                    const res = await modifyRoleInfo(this.editRoleForm)
                    if (res.hasOk) {
                        this.$message({
                            message: '角色删除成功',
                            type: 'success'
                        })
                        // 重置表格
                        this.getList()
                        this.$refs.editRoleForm.resetFields()
                        this.editRoleDialogVisible = false
                    } else {
                        this.$message({
                            message: res.message,
                            type: 'error'
                        })
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },

        // 获取全部菜单项
        async getAllMenuList () {
            const { data } = await getAllMenuList()
            this.allMenuList = data.menuList
        },

        // 编辑菜单权限取消
        editMenuCancel () {
            this.editMenuDialogVisible = false
            this.$refs.addRoleForm.resetFields()
        },

        // 编辑菜单权限提交
        async editMenuPost () {
            let childrenKey = this.$refs.menuTree.getCheckedKeys()
            let fatherKey = this.$refs.menuTree.getHalfCheckedKeys()
            let allKey = fatherKey.concat(childrenKey)
            const postObj = { roleCode: this.modifyMenuRoleCode, menu: allKey.toString() }
            const res = await modifyMenu(postObj)
            if (res.hasOk) {
                this.$message({
                    message: '菜单权限修改成功',
                    type: 'success'
                })
                // 重置表格
                this.getList()
                this.editMenuDialogVisible = false
            } else {
                this.$message({
                    message: res.message,
                    type: 'error'
                })
            }
        },

        // 选择菜单
        slectMenu () {
            this.getAllMenuList()
            this.innerMenuVisible = true
        },
        // 选择菜单弹窗取消
        selectMenuCancel () {
            this.innerMenuVisible = false
        },
        // 选择菜单弹窗确定
        selectMenuPost () {
            let childrenKey = this.$refs.addMenuTree.getCheckedKeys()
            let fatherKey = this.$refs.addMenuTree.getHalfCheckedKeys()
            let allKey = fatherKey.concat(childrenKey)
            this.addRoleForm.menu = allKey.toString()
            this.innerMenuVisible = false
        },
        // 新增角色取消
        addRoleFormCancel () {
            this.addRoleDialogVisible = false
            this.$refs.addRoleForm.resetFields()
        },
        // 新增角色提交
        addRoleFormPost () {
            this.$refs.addRoleForm.validate(async (valid) => {
                if (valid) {
                    const res = await addRole(this.addRoleForm)
                    if (res.hasOk) {
                        this.$message({
                            message: '角色新增成功',
                            type: 'success'
                        })
                        // 重置表格
                        this.getList()
                        this.$refs.addRoleForm.resetFields()
                        this.addRoleDialogVisible = false
                    } else {
                        this.$message({
                            message: res.message,
                            type: 'error'
                        })
                    }
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        sizeChange (limit) {
            this.limit = limit
            this.getList()
        },
        pageChange (offect) {
            this.offect = offect
            this.getList()
        }
    },
    created () {
        this.getList()
    },
}
</script>

<style lang="scss" scoped>
.loading {
    width: 100%;
    height: 100%;
}

.tip-contant {
    padding: 0 20px 0 0;
    margin-bottom: 20px;
    .icon {
        font-size: 24px;
        color: #e6a23c;
        margin-right: 10px;
        vertical-align: middle;
    }
}
::v-deep .el-dialog__body {
    padding-bottom: 0;
}
</style>